package joctave.toolbox.general;

import joctave.core.tokens.numbertokens.DoubleNumberToken;
import joctave.core.tokens.Token;
import joctave.core.tokens.OperandToken;
import joctave.core.functions.ExternalFunction;
import joctave.core.interpreter.GlobalValues;

/**An external function which checks if the argument is a struct*/
public class fft extends ExternalFunction
{
	
	
	
    public OperandToken evaluate(Token[] operands, GlobalValues globals)
    {

        if (getNArgIn(operands) != 1)
            throwMathLibException("fft: number of arguments != 1");
        
        if (!(operands[0] instanceof DoubleNumberToken))
            throwMathLibException("fft: not a number");
            
                

        double[][] val = ((DoubleNumberToken)operands[0]).getReValues();
        double[][] valt=new double[val[0].length][val.length];
        for (int i=0; i<val.length; i++)
        	for (int j=0; j<val[0].length; j++)
        		valt[j][i]=val[i][j];
        double[][] r = new double[val.length][val[0].length];
        double[][] im = new double[val.length][val[0].length];
      //  double[][] r = {{0.0}};
        //val[0]=new double []{1,2,3,4};
    	Complex []a=new Complex[val[0].length];
        for (int i=0; i<val.length; i++) {
        	for (int j=0; j<val[0].length; j++) 
	        	a[j]=new Complex(valt[i][j],0);// new  Complex [] { new Complex(1.0, 0.0),new Complex(2.0, 0.0)};//,new Complex(3.0, 0.0),new Complex(4.0, 0.0)};
	        Complex []x=fft(a);
        	for (int j=0; j<val[0].length; j++) { 
        		r[j][i]=x[j].re;
        		im[j][i]=x[j].im;
        	}
        }
       // for (int i=0; i<x.length; i++)
        //	System.out.println("qqq"+x[i].toString());
       // r[0] = fftMag( val[0] );
        //System.out.println("ssss"+r[0].length+" "+r[0][0]+" "+r[0][0]);
        return new DoubleNumberToken(r,im);

    
    }

   /* private int n, nu;

    private int bitrev(int j) {

        int j2;
        int j1 = j;
        int k = 0;
        for (int i = 1; i <= nu; i++) {
            j2 = j1/2;
            k  = 2*k + j1 - 2*j2;
            j1 = j2;
        }
        return k;
    }

    public  double[] fftMag(double[] x) {
        // assume n is a power of 2
        n = x.length;
        nu = (int)(Math.log(n)/Math.log(2));
        int n2 = n/2;
        int nu1 = nu - 1;
        double[] xre = new double[n];
        double[] xim = new double[n];
        double[] mag = new double[n2];
        double tr, ti, p, arg, c, s;
        for (int i = 0; i < n; i++) {
            xre[i] = x[i];
            xim[i] = 0.0;
        }
        int k = 0;

        for (int l = 1; l <= nu; l++) {
            while (k < n) {
                for (int i = 1; i <= n2; i++) {
                    p = bitrev (k >> nu1);
                    arg = 2 * (double) Math.PI * p / n;
                    c = (double) Math.cos (arg);
                    s = (double) Math.sin (arg);
                    tr = xre[k+n2]*c + xim[k+n2]*s;
                    ti = xim[k+n2]*c - xre[k+n2]*s;
                    xre[k+n2] = xre[k] - tr;
                    xim[k+n2] = xim[k] - ti;
                    xre[k] += tr;
                    xim[k] += ti;
                    k++;
                }
                k += n2;
            }
            k = 0;
            nu1--;
            n2 = n2/2;
        }
        k = 0;
        int r;
        while (k < n) {
            r = bitrev (k);
            if (r > k) {
                tr = xre[k];
                ti = xim[k];
                xre[k] = xre[r];
                xim[k] = xim[r];
                xre[r] = tr;
                xim[r] = ti;
            }
            k++;
        }

        mag[0] = (double) (Math.sqrt(xre[0]*xre[0] + xim[0]*xim[0]))/n;
        for (int i = 1; i < n/2; i++)
            mag[i]= 2 * (double) (Math.sqrt(xre[i]*xre[i] + xim[i]*xim[i]))/n;
        return mag;
    }*/
    
    
    /*************************************************************************
     *  Compilation:  javac Complex.java
     *  Execution:    java Complex
     *
     *  Data type for complex numbers.
     *
     *  The data type is "immutable" so once you create and initialize
     *  a Complex object, you cannot change it. The "final" keyword
     *  when declaring re and im enforces this rule, making it a
     *  compile-time error to change the .re or .im fields after
     *  they've been initialized.
     *
     *  % java Complex
     *  a            = 5.0 + 6.0i
     *  b            = -3.0 + 4.0i
     *  Re(a)        = 5.0
     *  Im(a)        = 6.0
     *  b + a        = 2.0 + 10.0i
     *  a - b        = 8.0 + 2.0i
     *  a * b        = -39.0 + 2.0i
     *  b * a        = -39.0 + 2.0i
     *  a / b        = 0.36 - 1.52i
     *  (a / b) * b  = 5.0 + 6.0i
     *  conj(a)      = 5.0 - 6.0i
     *  |a|          = 7.810249675906654
     *  tan(a)       = -6.685231390246571E-6 + 1.0000103108981198i
     *
     *************************************************************************/

    public class Complex {
        private final double re;   // the real part
        private final double im;   // the imaginary part

        // create a new object with the given real and imaginary parts
        public Complex(double real, double imag) {
            re = real;
            im = imag;
        }

        // return a string representation of the invoking Complex object
        public String toString() {
            if (im == 0) return re + "";
            if (re == 0) return im + "i";
            if (im <  0) return re + " - " + (-im) + "i";
            return re + " + " + im + "i";
        }

        // return abs/modulus/magnitude and angle/phase/argument
        public double abs()   { return Math.hypot(re, im); }  // Math.sqrt(re*re + im*im)
        public double phase() { return Math.atan2(im, re); }  // between -pi and pi

        // return a new Complex object whose value is (this + b)
        public Complex plus(Complex b) {
            Complex a = this;             // invoking object
            double real = a.re + b.re;
            double imag = a.im + b.im;
            return new Complex(real, imag);
        }

        // return a new Complex object whose value is (this - b)
        public Complex minus(Complex b) {
            Complex a = this;
            double real = a.re - b.re;
            double imag = a.im - b.im;
            return new Complex(real, imag);
        }

        // return a new Complex object whose value is (this * b)
        public Complex times(Complex b) {
            Complex a = this;
            double real = a.re * b.re - a.im * b.im;
            double imag = a.re * b.im + a.im * b.re;
            return new Complex(real, imag);
        }

        // scalar multiplication
        // return a new object whose value is (this * alpha)
        public Complex times(double alpha) {
            return new Complex(alpha * re, alpha * im);
        }

        // return a new Complex object whose value is the conjugate of this
        public Complex conjugate() {  return new Complex(re, -im); }

        // return a new Complex object whose value is the reciprocal of this
        public Complex reciprocal() {
            double scale = re*re + im*im;
            return new Complex(re / scale, -im / scale);
        }

        // return the real or imaginary part
        public double re() { return re; }
        public double im() { return im; }

        // return a / b
        public Complex divides(Complex b) {
            Complex a = this;
            return a.times(b.reciprocal());
        }

        // return a new Complex object whose value is the complex exponential of this
        public Complex exp() {
            return new Complex(Math.exp(re) * Math.cos(im), Math.exp(re) * Math.sin(im));
        }

        // return a new Complex object whose value is the complex sine of this
        public Complex sin() {
            return new Complex(Math.sin(re) * Math.cosh(im), Math.cos(re) * Math.sinh(im));
        }

        // return a new Complex object whose value is the complex cosine of this
        public Complex cos() {
            return new Complex(Math.cos(re) * Math.cosh(im), -Math.sin(re) * Math.sinh(im));
        }

        // return a new Complex object whose value is the complex tangent of this
        public Complex tan() {
            return sin().divides(cos());
        }
        


        // a static version of plus
      /*  public static Complex plus(Complex a, Complex b) {
            double real = a.re + b.re;
            double imag = a.im + b.im;
            Complex sum = new Complex(real, imag);
            return sum;
        }*/



        // sample client for testing
       /* public static void main(String[] args) {
            Complex a = new Complex(5.0, 6.0);
            Complex b = new Complex(-3.0, 4.0);

            System.out.println("a            = " + a);
            System.out.println("b            = " + b);
            System.out.println("Re(a)        = " + a.re());
            System.out.println("Im(a)        = " + a.im());
            System.out.println("b + a        = " + b.plus(a));
            System.out.println("a - b        = " + a.minus(b));
            System.out.println("a * b        = " + a.times(b));
            System.out.println("b * a        = " + b.times(a));
            System.out.println("a / b        = " + a.divides(b));
            System.out.println("(a / b) * b  = " + a.divides(b).times(b));
            System.out.println("conj(a)      = " + a.conjugate());
            System.out.println("|a|          = " + a.abs());
            System.out.println("tan(a)       = " + a.tan());
        }*/
        

    }
    
    // compute the FFT of x[], assuming its length is a power of 2
    public  Complex[] fft(Complex[] x) {
        int N = x.length;

        // base case
        if (N == 1) return new Complex[] { x[0] };

        // radix 2 Cooley-Tukey FFT
        if (N % 2 != 0) { throw new RuntimeException("N is not a power of 2"); }

        // fft of even terms
        Complex[] even = new Complex[N/2];
        for (int k = 0; k < N/2; k++) {
            even[k] = x[2*k];
        }
        Complex[] q = fft(even);

        // fft of odd terms
        Complex[] odd  = even;  // reuse the array
        for (int k = 0; k < N/2; k++) {
            odd[k] = x[2*k + 1];
        }
        Complex[] r = fft(odd);

        // combine
        Complex[] y = new Complex[N];
        for (int k = 0; k < N/2; k++) {
            double kth = -2 * k * Math.PI / N;
            Complex wk = new Complex(Math.cos(kth), Math.sin(kth));
            y[k]       = q[k].plus(wk.times(r[k]));
            y[k + N/2] = q[k].minus(wk.times(r[k]));
        }
        return y;
    }
    
    
}

/*
@GROUP
general
@SYNTAX
fft(values)
@DOC
@EXAMPLES
fft(sin([1:255]))
@NOTES
@SEE
*/
